from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.common.action_chains import ActionChains
import time
import pandas as pd
import os

class Grap:  # 类名应该以大写字母开头
    def __init__(self):
        # 设置驱动，selenium的新用法
        self.service = Service(r"C:\Program Files\Google\Chrome\Application\chromedriver.exe") 
        # 实例化浏览器对象
        self.driver = webdriver.Chrome(service=self.service)
        self.df = pd.DataFrame(
            columns=["id", "title", "score", "star", "year", "duration", "director", "actors", "vote"])

        self.df_save_path = "./data/nowplay.csv"
        self.sc_df = pd.DataFrame(columns=["rating", "comment"])
        self.sc_save_path = "./data/short_comments.csv"

        # 检查并创建目录
        os.makedirs(os.path.dirname(self.df_save_path), exist_ok=True)

    def get_nowplaying(self):
        self.driver.get("https://movie.douban.com/cinema/nowplaying/leshan/")
        time.sleep(2)

        elements = self.driver.find_elements(By.XPATH, "//ul[@class='lists']/li[@class='list-item']")

        # 初始化计数器
        for i, ele in enumerate(elements):
            did = ele.get_attribute("id")
            didtitle = ele.get_attribute("data-title")
            dscore = ele.get_attribute("data-score")
            dstar = ele.get_attribute("data-star")
            dyear = ele.get_attribute("data-year")
            ddura = ele.get_attribute("data-duration")
            ddirector = ele.get_attribute("data-director")
            dactors = ele.get_attribute("data-actors")
            dvote = ele.get_attribute("data-votecount")

            self.df.loc[i] = [did, didtitle, dscore, dstar, dyear, ddura, ddirector, dactors, dvote]

        self.df.to_csv(self.df_save_path, index=None)

    def get_short_comment(self):
        self.driver.get("https://movie.douban.com/cinema/nowplaying/leshan/")
        time.sleep(2)  # 等待页面加载

        a = 0
        while True:  # 使用无限循环，直到手动退出
            elements1 = self.driver.find_elements(By.XPATH, "//span[@class='short']")
            elements2 = self.driver.find_elements(By.XPATH, "//span[@class='comment-info']/span[@class='rating']")

            for ele1, ele2 in zip(elements1, elements2):
                comment = ele1.text
                rating = ele2.get_attribute("title")
                self.sc_df.loc[a] = [rating, comment]
                a += 1

            # 尝试获取下一页的评论
            next_ele = self.driver.find_elements(By.XPATH, "//div[@id='paginator']/a")

            # 检查是否有足够的分页链接
            if len(next_ele) > 2:
                try:
                    link = next_ele[2].get_attribute("href")
                    self.driver.get(link)
                    time.sleep(2)  # 等待新页面加载
                except Exception as e:
                    print("访问下一页时出错:", e)
                    break  # 退出循环
            else:
                print("没有更多评论或分页链接不足.")
                break  # 退出循环

        # 保存短评到 CSV 文件
        self.sc_df.to_csv(self.sc_save_path, index=None)

    def close(self):
        self.driver.quit()


# 使用示例
if __name__ == "__main__":
    grap = Grap()
    grap.get_nowplaying()  # 先获取正在上映的电影信息
    grap.get_short_comment()  # 然后获取短评
    grap.close()
